package com.qst.rongxiaoserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.rongxiaoserver.mapper.AddressMapper;
import com.qst.rongxiaoserver.model.AddressModel;
import com.qst.rongxiaoserver.service.IAddressService;
import org.springframework.stereotype.Service;

import java.util.List;

// 实现类
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, AddressModel> implements IAddressService {


    private final AddressMapper addressMapper;

    public AddressServiceImpl(AddressMapper addressMapper) {
        this.addressMapper = addressMapper;
    }

    @Override
    public List<AddressModel> getAddressListByName(String ownName) {
//        this - > AddressMapper的实例化对象
        LambdaQueryWrapper<AddressModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressModel::getOwnName, ownName); // 精确查询
        return this.list(queryWrapper);
    }

    // 获取当前登录用户的默认地址
    @Override
    public AddressModel getDefaultAddressByName(String ownName) {
        LambdaQueryWrapper<AddressModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressModel::getOwnName, ownName); // 精确查询
        queryWrapper.eq(AddressModel::getIsDefault, 1); // 精确查询 isDefault=1
        return this.getOne(queryWrapper);
    }
    @Override
    public boolean setDefaultAddress(Integer id, String ownName) {
        // 1. 找到之前的默认地址， 并将其 isDefault 设置为 0
        AddressModel address1 = getDefaultAddressByName(ownName);   // 找到之前的默认地址

        if (address1 != null) {
            address1.setIsDefault(0);
            this.updateById(address1);  // 更新之前的默认地址
        }
        // 2. 将指定 id 的地址的 isDefault 设为 1
        AddressModel addressModel = new AddressModel();
        addressModel.setId(id);
        addressModel.setIsDefault(1);
        return this.updateById(addressModel);
    }
}
